package login;

import javax.swing.*;
import java.awt.event.*;
import java.util.List;
import gui.LibraryMainFrame;
import utils.FileUtils;

public class LoginFrame extends JFrame implements ActionListener {
    private JTextField userField;
    private JPasswordField passField;
    private JButton loginButton;
    private JButton registerButton;
    private static final String FILE_NAME = "users.txt";

    public LoginFrame() {
        setTitle("登录");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(null);

        JLabel userLabel = new JLabel("用户名:");
        userLabel.setBounds(30, 20, 80, 25);
        add(userLabel);

        userField = new JTextField(20);
        userField.setBounds(110, 20, 150, 25);
        add(userField);

        JLabel passLabel = new JLabel("密码:");
        passLabel.setBounds(30, 60, 80, 25);
        add(passLabel);

        passField = new JPasswordField(20);
        passField.setBounds(110, 60, 150, 25);
        add(passField);

        loginButton = new JButton("登录");
        loginButton.setBounds(80, 100, 80, 30);
        loginButton.addActionListener(this);
        add(loginButton);

        registerButton = new JButton("注册");
        registerButton.setBounds(170, 100, 80, 30);
        registerButton.addActionListener(this);
        add(registerButton);

        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == loginButton) {
            String username = userField.getText();
            String password = new String(passField.getPassword());

            List<User> users = FileUtils.readUsersFromFile(FILE_NAME);
            for (User user : users) {
                if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
                    JOptionPane.showMessageDialog(this, "登录成功！");
                    dispose();
                    new LibraryMainFrame();
                    return;
                }
            }
            JOptionPane.showMessageDialog(this, "用户名或密码错误！", "错误", JOptionPane.ERROR_MESSAGE);
        } else if (e.getSource() == registerButton) {
            new RegisterFrame();
        }
    }
}